package de.se.ludoapp.activity.task;

import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.activity.NewGameActivity;
import de.se.ludoapp.activity.PlayerTableActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameResponse;

/**
 * Task to get answer, if request is acceptet.
 * 
 * @author Marlen Rotert
 * 
 */
public class IsRequestingPlayerAcceptedRequestTask extends
		AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private PlayerTableActivity context;
	private Game gameOfRequest;

	public IsRequestingPlayerAcceptedRequestTask(LudoApplication ludoApp,
			PlayerTableActivity context, Game gameOfRequest) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.gameOfRequest = gameOfRequest;
	}

	/**
	 * sent request for game to server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute allowUserToEnterTheGame */
		GameResponse gameResponse = ludoApp.getLudoStub()
				.isTheRequestingPlayerAccepted(
						ludoApp.getlogedinUser().getSessionId(),
						gameOfRequest.getGameId());
		if (gameResponse.getReturnCode() == 0) {
			Game game = gameResponse.getGame();
			ludoApp.setCurrentGame(game);
		}
		return gameResponse.getMsg();
	}

	/**
	 * Show Activities whether you will accept or not. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		if (ludoApp.getCurrentGame() != null) {
			Toast.makeText(context, result, Toast.LENGTH_LONG).show();
			Intent intentJoinNewGame = new Intent(context,
					NewGameActivity.class);
			intentJoinNewGame.putExtra("OpenNewGame", false);
			context.startActivity(intentJoinNewGame);
			context.finish();
		} else {
			new RemoveRequestForGameTask(ludoApp, context, gameOfRequest)
					.execute();
		}
	}
}
